<?php

namespace App\Http\Controllers\Admin;

use App\Http\Config\ErrorCode;
use App\Http\Config\WechatAPI;
use App\Library\Tools;
use App\Library\UpTools;
use App\Models\Admin\AdminUser;
use App\Models\Admin\Configs;
use App\Models\Company;
use App\Models\User\UserBase;
use App\Models\User\UserWechat;
use App\Models\Wechat;
use Illuminate\Http\Request;
use Excel;
use Illuminate\Support\Facades\DB;

class HrController extends BaseController
{
    protected $admin_user_fields = [
        'name'  => '',
        'company_id' => '',
        'position'   => '',
        'sex' => '男',
        'email' => '',
        'formal_time' => '',
        'hiredate' => '',
        'wechat_pic' => '',
    ];

    protected $admin_user_extend_fields = [
        'birth_date'=> '',
        'nation' => '',
        'age' => 0,
        'idcard_no'   => '',
        'highest_edu'   => '',
        'degree'   => '',
        'marital_status'   => '',
        'stature'   => '',
        'political_affiliation' => '',
        'native_place' => '',
        'reg_permanent_place' => '',
        'reg_permanent_type' => '',
        'technical_title' => '',
        'social_security_no' => '',
        'public_reserve_funds' => '',
        'current_address' => '',
        'home_address' => '',
        'mobile_phone' => '',
        'tel_phone' => '',
        'binduser_name' => '',
        'binduser_work_address' => '',
        'binduser_phone' => '',
        'education_history' => '',
        'work_history' => '',
        'foreigner_language' => '',
        'foreigner_language_status' => '',
        'computer_science_level' => '',
        'skill_title' => '',
        'cantonese_skill_status' => '',
        'certificate_info' => '',
        'lastest_employer_name' => '',
        'lastest_employer_job' => '',
        'lastest_employer_phone' => '',
        'family_info' => '',
        'acquaintance_name' => '',
        'acquaintance_department' => '',
        'acquaintance_job' => '',
        'acquaintance_relation' => '',
        'job_status' => '',
        'form_pic' => '',
        'real_avatar' => '',
        'identity_card_pic' => '',
        'certificate_pic' => '',
        'examination_pic' => '',
        'other_pic' => '',
        'goods_collection' => '',
        'job_number' => '',
        'grade' => '',
        'application_form_pic' => ''
    ];

    public function __construct(Request $request){
        parent::__construct($request);
    }

    public function getDataList(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $pageno = $request->post("page_no", 1);
        $pagesize = $request->post("page_size", 10);
        $searchFilter = array(
            'sortName' => $request->post("sortName"), //排序列名
            'sortOrder' => $request->post("sortOrder", "desc"), //排序（desc，asc）
            'pageNumber' => $pageno, //当前页码
            'pageSize' => $pagesize, //一页显示的条数
            'start' => ($pageno-1) * $pagesize, //开始位置
            'status' => $request->post("status",''),
            'hireDate' => $request->post("hireDate",''),
            'job_status' => $request->post("job_status",''),
            'searchKey' => trim($request->post("search",'')), //搜索条件
            'company_id' => $request->post("company_id",''),
            'admin_id' => $this->AU['position'] == "超级管理员" ? "" : $this->AU['id']
        );
        $adminUserModel = new AdminUser();
        $res = $adminUserModel->getAdminUserListFromHr($searchFilter);
        foreach ($res["rows"] as &$item){
            $item = $this->doTrans($item);
        }
        $this->returnData['data'] = $res;
        return $this->return_result($this->returnData);
    }

    public function doTrans($data){
        static $annualLeave;
        if(empty($annualLeave)){
            $annualLeave = DB::table("annual_leave")->where("mall_id", request()->mallData["id"])->first();
        }
        $data["annual_leave"] = 0;
        $tempData = strtotime(date('Y-'.($annualLeave->day_lapse ? ($annualLeave->day_lapse > 9 ? ($annualLeave->day_lapse > 12 ? "12" : $annualLeave->day_lapse) : "0{$annualLeave->day_lapse}") : '01' ).'-01'));
        if($data["job_status"] == '1' && $tempData > time()) {
            $hiredate = strtotime($data["hiredate"]);
            if ($day = intval($annualLeave->rule)) {
                if ($hiredate + $day * 86400 <= time()) {
                    $data["annual_leave"] = $data["annual_leave"] + $annualLeave->day_count;
                }
            } else {
                $data["annual_leave"] = $data["annual_leave"] + $annualLeave->day_count;
            }
            $data["annual_leave"] = $data["annual_leave"] + intval((time() - $hiredate) / 86400 / 30 / 12) * intval($annualLeave->year_add);
            $data["annual_leave"] = $data["annual_leave"] > $annualLeave->max_day ? $annualLeave->max_day : $data["annual_leave"];
        }
        return $data;
    }

    public function getInfo($id){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        if(!$id){
            return $this->return_result(ErrorCode::$admin_enum['params_error']);
        }
        $adminUserModel = new AdminUser();
        $res = $adminUserModel->getAdminUserDetail($id);
        if (!$res) {
            return $this->return_result(ErrorCode::$admin_enum['not_exist']);
        }
        $res = $this->doTrans($res);
        $data['uid'] = $id;
        $companyModel = new Company();
        $company = $companyModel->getCompanyByID($res['company_id']);
        $res['companys_name'] = $company['name'];
        if ($res['real_avatar']){
            $res['real_avatar'] = $this->processingPictures($res['real_avatar']);
        }
        if ($res['wechat_pic']){
            $res['wechat_pic'] = $this->processingPictures($res['wechat_pic']);
        }
        if ($res['application_form_pic']){
            $res['application_form_pic'] = json_decode($res['application_form_pic'], true);
            foreach ($res['application_form_pic'] as &$item){
                $item = $this->processingPictures($item);
            }
        }
        if (isset($res['identity_card_pic'])){
            $res['identity_card_pic'] = json_decode($res['identity_card_pic'],true);
            foreach ($res['identity_card_pic'] as &$v){
                $v = $this->processingPictures($v);
            }
        }else{
            $res['identity_card_pic'] = [];
        }
        if (isset($res['other_pic'])){
            $res['other_pic'] = json_decode($res['other_pic'],true);
            foreach ($res['other_pic'] as &$v){
                $v = $this->processingPictures($v);
            }
        }
        if (isset($res['examination_pic'])){
            $res['examination_pic'] = json_decode($res['examination_pic'],true);
            foreach ($res['examination_pic'] as &$v){
                $v = $this->processingPictures($v);
            }
        }
        if (isset($res['certificate_pic'])){
            $res['certificate_pic'] = json_decode($res['certificate_pic'],true);
            foreach ($res['certificate_pic'] as &$v){
                $v = $this->processingPictures($v);
            }
        }
        if ($res['form_pic']){
            $res['form_pic'] = json_decode($res['form_pic'],true);
            foreach ($res['form_pic'] as &$v){
                $v = $this->processingPictures($v);
            }
        }else{
            $res['form_pic'] = array();
        }
        $data['user_data'] = $res;
        $this->returnData['data'] = $data;
        return $this->return_result($this->returnData);
    }

    public function update(Request $request,$id){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        if((int)$id===1){
            $this->returnData = 0;
            $this->returnData['msg'] = "无权编辑该用户";
            return $this->return_result($this->returnData);
        }
        $res = $request->input();
        foreach ($res as $key=>$value){
            if(isset($this->admin_user_fields[$key])){
                $data[$key] = $value;
            }
            if(isset($this->admin_user_extend_fields[$key])){
                $extend_data[$key] = $value;
            }
        }
        $userData = AdminUser::query()->where("id", $id)->first();
        if(empty($userData)){
            return ErrorCode::code("customized", "用户不存在");
        }
        $data['status'] = $extend_data['job_status'] == '1' ? 0 : 1;
        if ($userData->company_id != $data['company_id']) { // 修改部门
            $qyUserData = Wechat::getInstance()->buildQYUserWechat(["userid" => $userData->wechat_id], "get");
            if ($qyUserData['errcode'] == 0) {
                $data['main_department'] = $qyUserData['main_department'];
                $companyModel = new Company();
                if (!$companyData = $companyModel->getCompanyByID($data['company_id'])) {
                    return $this->return_result(ErrorCode::code("customized", "公司不存在"));
                }
                $companyData['wechat_channel_id'] = empty($companyData['wechat_channel_id']) ? 1 : $companyData['wechat_channel_id'];
                $wechatId = 0;
                do {
                    $data["department"] = [$wechatId ?: $companyData['wechat_channel_id']];
                    $res = UserWechat::getInstance()->updateQYUser($userData->wechat_id, $data);
                } while ($res['errcode'] == '40066' && !$wechatId && $wechatId = 1);
                if ($res['errcode'] != 0) {
                    throw new \Exception("企业微信消息：" . (isset(WechatAPI::$qyWx_msg[$res['errcode']]) ? WechatAPI::$qyWx_msg[$res['errcode']] : $res['errmsg']));
                }
            }
        }
        $adminUserModel = new AdminUser();
        $res = $adminUserModel->adminUserUpdate((int)$id,$data);
        $extend_res = $adminUserModel->adminUserExtendUpdate((int)$id,$extend_data);
        if(!$res && !$extend_res){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = "更新资料失败";
            return $this->return_result($this->returnData);
        }
        $this->returnData['msg'] = "更新资料成功";
        return $this->return_result($this->returnData);
    }

    /* 暂不用，后面再处理 */
    public function insert(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $res = $request->input();
        foreach ($res as $key=>$value){
            if(isset($this->admin_user_fields[$key])){
                $data[$key] = $value;
            }
            if(isset($this->admin_user_extend_fields[$key])){
                $extend_data[$key] = $value;
            }
        }
        $data['password'] = bcrypt($res['password'] ?: "123456");
        $adminUserModel = new AdminUser();
        $id = $adminUserModel->adminUserInsert($data);
        $extend_res = $adminUserModel->adminUserExtendUpdate((int)$id,$extend_data);
        if(!$id && !$extend_res){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = "插入资料失败";
            return $this->return_result($this->returnData);
        }
        $this->returnData['msg'] = "插入资料成功";
        return $this->return_result($this->returnData);
    }

    public function del($id){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $adminUserModel = new AdminUser();
        $res = $adminUserModel->adminUserDelete($id);
        if(!$res){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = "删除资料失败";
            return $this->return_result($this->returnData);
        }
        $this->returnData['msg'] = "删除资料成功";
        return $this->return_result($this->returnData);
    }

    // 获取企业微信打卡记录
    public function getPunchCardRecordList(Request $request, $return = true){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $companyId = $request->post("companyId", '');
        if(empty($id = $request->post("id"))){
            $res = DB::table('admin_users as au')
                ->select('au.wechat_id',"au.name", 'c.name as company_name')
                ->leftJoin('admin_users_extend as aue','au.id','=','aue.admin_id')
                ->leftJoin('company as c','au.company_id','=','c.id')
                ->where('aue.job_status',1);
        }else{
            $res = DB::table('admin_users as au')
                ->select('au.wechat_id',"au.name",'c.name as company_name')
                ->leftJoin('company as c','au.company_id','=','c.id')
                ->where("au.id", $id);
        }
        if($companyId!=''){$res->where('au.company_id',$companyId);}
        if($this->AU['position'] != "超级管理员"){
            $tt = DB::table('permissions as p')
                ->leftJoin('admin_permission_role as pr','pr.permission_id','=','p.id')
                ->leftJoin('admin_role_user as ru','ru.role_id','=','pr.role_id')
                ->where("ru.user_id", $this->AU["id"])
                ->where("p.name", "admin.hr.allAttendance")
                ->count();
            if(!$tt) {
                $adminUserModel = new UserBase();
                $user_list = $adminUserModel->getAdminSubuser($this->AU["id"]);
                $res->whereIn('au.id', $user_list);
            }
        }
        $temp = json_decode(json_encode($res->where("au.mall_id", $request->mallData["id"])->skip(0)->take(99)->orderBy("au.created_at", "desc")->get()),true);
        if(!empty($temp)) {
            $userList = '';
            foreach ($temp as $item) {
                $userList .= $item["wechat_id"].",";
                $email[$item["wechat_id"]] = $item;
            }
            $userList = substr($userList, 0, -1);
        }
        if(empty($userList)){
            $this->returnData['data'] = [];
            return $return ? $this->return_result($this->returnData) : $this->returnData;
        }
        $startTime = $request->post("startTime");
        $endTime = $request->post("endTime");
        if(empty($startTime) || empty($endTime)){
            $startTime = mktime(0,0,0,date('m'),date('d'),date('Y'));
            $endTime = $startTime + 86400;
        }elseif($startTime == $endTime){
            $endTime = $startTime + 86400;
        }
        $config = Configs::query()->where("mall_id", $request->mallData["id"])->first();
        $url = WechatAPI::$qywx_conf['get_token'].'?corpid='.$config->company_id.'&corpsecret='.$config->punch_secret;
        $get_token_res = file_get_contents($url);
        $get_token_res = json_decode($get_token_res,true);
        $data = [
            "opencheckindatatype" => 3, "starttime" => $startTime, "endtime" => $endTime, "useridlist" => explode(",", $userList)
        ];
        $url = WechatAPI::$qywx_conf['punch_card'].'?access_token='.$get_token_res['access_token'];
        $res = Tools::curl($url, json_encode($data));
        $res = json_decode($res,true);
        if($res["errcode"] != '0'){
            $this->returnData['data'] = [];
        }else{
            foreach ($res["checkindata"] as &$item){
                $time = date("Y-m-d", $item["checkin_time"]);
                if(!isset($newData[$item["userid"]."-".$time])) {
                    $newData[$item["userid"] . "-" . $time] = [
                        "userid" => $item["userid"], "name" => $email[$item["userid"]]["name"], "company_name" => $email[$item["userid"]]["company_name"],
                        "groupname" => $item["groupname"], "start_time" => date("H:i", $item["checkin_time"]),
                        "time" => $time, "count" => 1, "exception_type" => $item["exception_type"]
                    ];
                }else{
                    $newData[$item["userid"] . "-" . $time]["end_time"] = date("H:i", $item["checkin_time"]);
                    $newData[$item["userid"] . "-" . $time]["count"]++;
                    if(($newData[$item["userid"] . "-" . $time]["exception_type"] == '正常') && $item["exception_type"] != '' && $item["exception_type"] != "正常"){
                        $newData[$item["userid"] . "-" . $time]["exception_type"] = $item["exception_type"];
                    }
                }
                if(empty($newData[$item["userid"] . "-" . $time]["exception_type"])){
                    $newData[$item["userid"] . "-" . $time]["exception_type"] = "正常";
                }
                $newData[$item["userid"] . "-" . $time]["detail"][] = $item;
            }
            $status = $request->post("status", '');
            if($status != '') {
                foreach ($newData as $key => $item) {
                    if ($status == '1') {
                        if ($item["exception_type"] != '正常') {
                            unset($newData[$key]);
                        }
                    } else {
                        if ($item["exception_type"] == '正常') {
                            unset($newData[$key]);
                        }
                    }
                }
            }
            if(!empty($newData)) {
                $this->returnData['data'] = array_values($this->array_sort(array_values($newData), "time", "SORT_DESC"));
            }else{
                $this->returnData['data'] = [];
            }
        }
        return $return ? $this->return_result($this->returnData) : $this->returnData;
    }

    public function array_sort($array, $column, $sort = 'SORT_ASC'){
        $new_array = array();
        $sort_array = array();
        foreach ($array as $key => $value) {
            if (!is_array($value)) {
                $sort_array[$key] = $value;
            } else {
                if(isset($value[$column])){
                    $sort_array[$key] = $value[$column];
                }
            }
        }
        switch ($sort) {
            case 'SORT_ASC':
                asort($sort_array);
                break;
            case 'SORT_DESC':
                arsort($sort_array);
                break;
        }
        foreach ($sort_array as $key => $value) {
            $new_array[$key] = $array[$key];
        }
        return $new_array;
    }

    // 导出
    public function punchCardRecordToExcel(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $res = $this->getPunchCardRecordList($request, false);
        if($res["code"] != '0'){
            return $this->return_result($res);
        }
        $arr[] = ['时间','姓名','部门','所属规则','最早','最晚','打卡次数','状态'];
        foreach ($res["data"] as $k=>&$v) {
            $arr[] = [
                $v['time'],
                $v['name'],
                $v['company_name'],
                $v['groupname'],
                $v['start_time'],
                isset($v['end_time'])?$v['end_time']: "",
                $v['count'],
                $v['exception_type'],
            ];
        }
        $con = Configs::query()->where("mall_id", $request->mallData["id"])->first();
        if ($con->env == 'CLOUD'){
            $temp_file = tempnam(sys_get_temp_dir(),time().".xlsx");  //临时文件
            $a = Excel::create('打卡信息',function($excel) use ($arr){
                $excel->sheet('打卡信息', function ($sheet) use ($arr) {
                    $sheet->rows($arr);
                });
            })->string('xlsx');
            file_put_contents($temp_file,$a);
            $data['code'] = 3;
            $data['name'] = '打卡信息.xlsx';
            $data['data'] = $temp_file;
            return $data;
        }else{
            Excel::create('打卡信息',function($excel) use ($arr){
                $excel->sheet('打卡信息', function ($sheet) use ($arr) {
                    $sheet->rows($arr);
                });
            })->export('xlsx');
        }
    }
}
